package com.blockmeta.bbs.minemodule.activity;

import android.content.Context;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ToggleButton;
import android.widget.ViewSwitcher;

import com.blockmeta.bbs.baselibrary.net.callback.MyStringCallback;
import com.blockmeta.bbs.baselibrary.utils.SharedPreferenceUtil;
import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.gson.GsonUtil;
import com.blockmeta.bbs.baselibrary.widget.tab.OnTabSelectListener;
import com.blockmeta.bbs.baselibrary.widget.tab.SlidingTabLayout;
import com.blockmeta.bbs.businesslibrary.adapter.InforListAdapter;
import com.blockmeta.bbs.businesslibrary.arouter.RouterHelper;
import com.blockmeta.bbs.businesslibrary.arouter.RouterPath;
import com.blockmeta.bbs.businesslibrary.base.BaseActivity;
import com.blockmeta.bbs.businesslibrary.constant.Constant;
import com.blockmeta.bbs.businesslibrary.constant.NetConstant;
import com.blockmeta.bbs.businesslibrary.net.pojo.ErrorPOJO;
import com.blockmeta.bbs.businesslibrary.net.pojo.InforPOJO;
import com.blockmeta.bbs.businesslibrary.util.AccountHelper;
import com.blockmeta.bbs.minemodule.R;
import com.blockmeta.bbs.minemodule.R2;
import com.blockmeta.bbs.minemodule.adapter.BBSCollectionListAdapter;
import com.blockmeta.bbs.minemodule.pojo.BBSLatestPOJO;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.zhy.http.okhttp.OkHttpUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.MediaType;

public class MyCollectionActivity extends BaseActivity implements  CompoundButton.OnCheckedChangeListener , OnTabSelectListener {

    @BindView(R2.id.tgb_edit)
    ToggleButton mTgbEdit;
    @BindView(R2.id.tab_layout)
    SlidingTabLayout mTabLayout;
    @BindView(R2.id.rcv_news)
    RecyclerView mRcvNews;
    @BindView(R2.id.rcv_bbs)
    RecyclerView mRcvBbs;
    @BindView(R2.id.view_switcher)
    ViewSwitcher mViewSwitcher;
    @BindView(R2.id.btn_delete)
    Button mBtnDelete;
    private Context mContext;
    private InforListAdapter inforListAdapter;
    private BBSCollectionListAdapter mBBSListAdapter;
    private InforPOJO listBean;
    private BBSLatestPOJO latestPOJO;
    private int newsPageNo = 1;
    private int bbsPageNo = 1;
    private List<InforPOJO.ListBean> newsList = new ArrayList<>();
    private List<BBSLatestPOJO.ListBean> bbsList = new ArrayList<>();

    @Override
    protected boolean showTitle() {
        return false;
    }

    @Override
    public View setView() {
        mContext = this;
        return LayoutInflater.from(this).inflate(R.layout.activity_my_collection, null);
    }

    @Override
    protected void initialize() {
        super.initialize();
        mTabLayout.addTabs(new String[]{"社区论坛","新闻资讯"});
        mTabLayout.setOnTabSelectListener(this);
        mTgbEdit.setOnCheckedChangeListener(this);
        //news收藏列表
        initNewsList();
        //bbs收藏列表
        initBbsList();
    }

    private void initBbsList() {
        mRcvBbs.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        mBBSListAdapter = new BBSCollectionListAdapter(R.layout.item_bbs_list_item, bbsList, mContext);
        mRcvBbs.setAdapter(mBBSListAdapter);

        mBBSListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                try {
                    RouterHelper.buildPath(RouterPath.BBS_DETAIL_ACTIVITY)
                            .withString("tid",latestPOJO.getList().get(position).getTid()+"")
                            .navigation(mContext);
                } catch (Exception e) {
                    return;
                }
            }
        });
        mBBSListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                ++bbsPageNo;
                OkHttpUtils.get()
                        .addHeader("from", "android")
                        .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                        .addHeader("uid", AccountHelper.getUid())
                        .url(NetConstant.GET_COLLECTION_BBS + "?num=20&page=" + bbsPageNo + "&type=all &uid=" + AccountHelper.getUid())
                        .build()
                        .execute(new MyStringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                ToastUtil.show("联网失败，请检查网络");
                                //关闭加载更多
                                mBBSListAdapter.loadMoreEnd(true);
                                --bbsPageNo;
                            }

                            @Override
                            public void onResponse(String response, int id) {
                                mBBSListAdapter.loadMoreComplete();
                                latestPOJO = GsonUtil.buildGson().fromJson(response, BBSLatestPOJO.class);
                                if (latestPOJO == null || latestPOJO.getList() == null || latestPOJO.getList().size() == 0) {
                                    //关闭加载更多
                                    mBBSListAdapter.loadMoreEnd(true);
                                    --bbsPageNo;
                                    return;
                                }
                                bbsList.addAll(latestPOJO.getList());
                                mBBSListAdapter.notifyDataSetChanged();
                            }
                        });
            }
        }, mRcvBbs);
        getCollectionBBS();
    }

    private void initNewsList() {
        mRcvNews.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        inforListAdapter = new InforListAdapter(newsList, mContext);

        mRcvNews.setAdapter(inforListAdapter);

        inforListAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                ++newsPageNo;
                OkHttpUtils.get()
                        .addHeader("from", "android")
                        .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                        .addHeader("uid", AccountHelper.getUid())
                        .url(NetConstant.GET_COLLECTION_NEWS + newsPageNo)
                        .build()
                        .execute(new MyStringCallback() {
                            @Override
                            public void onError(Call call, Exception e, int id) {
                                //关闭加载更多
                                inforListAdapter.loadMoreEnd(true);
                                --newsPageNo;
                            }
                            @Override
                            public void onResponse(String response, int id) {
                                listBean = GsonUtil.buildGson().fromJson(response, InforPOJO.class);
                                if (listBean == null || listBean.getList() == null || listBean.getList().size() == 0) {
                                    //关闭加载更多
                                    inforListAdapter.loadMoreEnd(true);
                                    --newsPageNo;
                                    return;
                                }
                                newsList.addAll(listBean.getList());
                                inforListAdapter.notifyDataSetChanged();
                            }
                        });
            }
        }, mRcvNews);
        //getCollectionNews();
    }

    //获取收藏的新闻
    private void getCollectionNews() {
        newsPageNo = 1;
        newsList.clear();
        OkHttpUtils.get()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.GET_COLLECTION_NEWS + newsPageNo)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        View view = LayoutInflater.from(mContext).inflate(R.layout.empty_net, null);
                        ImageView reconn = (ImageView) view.findViewById(R.id.click_reconn);
                        reconn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getCollectionNews();
                            }
                        });
                        inforListAdapter.setEmptyView(view);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        inforListAdapter.loadMoreComplete();
                        listBean = GsonUtil.buildGson().fromJson(response, InforPOJO.class);

                        if (listBean.getList() == null || listBean.getList().size() == 0) {
                            View view = LayoutInflater.from(mContext).inflate(R.layout.empty_data, null);
                            inforListAdapter.setEmptyView(view);
                            return;
                        }
                        newsList.addAll(listBean.getList());
                        inforListAdapter.notifyDataSetChanged();
                    }
                });
    }

    //获取收藏的帖子
    private void getCollectionBBS() {
        bbsPageNo = 1;
        bbsList.clear();
        OkHttpUtils.get()
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .url(NetConstant.GET_COLLECTION_BBS + "?num=20&page=" + bbsPageNo + "&type=all&uid=" + AccountHelper.getUid())
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        View view = LayoutInflater.from(mContext).inflate(R.layout.empty_net, null);
                        ImageView reconn = (ImageView) view.findViewById(R.id.click_reconn);
                        reconn.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                getCollectionNews();
                            }
                        });
                        mBBSListAdapter.setEmptyView(view);
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        latestPOJO = GsonUtil.buildGson().fromJson(response, BBSLatestPOJO.class);
                        if (latestPOJO == null || latestPOJO.getList() == null || latestPOJO.getList().size() == 0) {
                            View view = LayoutInflater.from(mContext).inflate(R.layout.empty_data, null);
                            inforListAdapter.setEmptyView(view);
                            return;
                        }
                        bbsList.addAll(latestPOJO.getList());
                        mBBSListAdapter.notifyDataSetChanged();
                    }
                });
    }

    @OnClick({R2.id.ll_back, R2.id.btn_delete})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.ll_back) {
            finish();

        } else if (i == R.id.btn_delete) {
            mTgbEdit.setChecked(false);

            if (mTabLayout.getCurrentTab() == 0) {
                //删除帖子
            } else {
                //删除新闻资讯
                deleteNews();
            }
        }
    }

    /**
     * 删除新闻资讯
     */
    private void deleteNews() {
        StringBuilder ids = new StringBuilder("{\"ids\":\"");
        int size = newsList.size();
        final ArrayList<InforPOJO.ListBean> deletedList = new ArrayList<>();
        for (int i = 0; i < size; i++) {
            if (newsList.get(i).isSelected()) {
                InforPOJO.ListBean bean = newsList.get(i);
                ids.append(bean.getId()).append(",");
                deletedList.add(bean);
            }
        }
        int index = ids.lastIndexOf(",");
        if (index == -1) {return;}
        ids.deleteCharAt(index).append("\"}");
        OkHttpUtils.postString()
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .addHeader("from", "android")
                .addHeader("token", SharedPreferenceUtil.getString(mContext, Constant.TOKEN, ""))
                .addHeader("uid", AccountHelper.getUid())
                .content(ids.toString())
                .url(NetConstant.DELETE_COLLECTION_NEWS)
                .build()
                .execute(new MyStringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        ToastUtil.show("操作失败，请检查网络");
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        if (code != 200) {
                            ErrorPOJO errorPOJO = GsonUtil.buildGson().fromJson(response, ErrorPOJO.class);
                            ToastUtil.show(errorPOJO.getMessage());
                            return;
                        }
                        newsList.removeAll(deletedList);
                        inforListAdapter.notifyDataSetChanged();
                    }
                });
    }


    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            mBtnDelete.setVisibility(View.VISIBLE);
            mTabLayout.setTabClickable(false);
            if (mTabLayout.getCurrentTab() == 0) {
                mBBSListAdapter.setEditStatus(true);
                mBBSListAdapter.notifyDataSetChanged();
            } else {
                inforListAdapter.setEditStatus(true);
                inforListAdapter.notifyDataSetChanged();
            }
        } else {
            mBtnDelete.setVisibility(View.GONE);
            mTabLayout.setTabClickable(true);
            if (mTabLayout.getCurrentTab() == 0) {
                mBBSListAdapter.setEditStatus(false);
                mBBSListAdapter.notifyDataSetChanged();
            } else {
                inforListAdapter.setEditStatus(false);
                inforListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onTabSelect(int position) {
        if (position == 0) {
            mTgbEdit.setVisibility(View.GONE);
            mViewSwitcher.showNext();
            getCollectionBBS();
        } else {
            mTgbEdit.setVisibility(View.VISIBLE);
            mViewSwitcher.showPrevious();
            getCollectionNews();
        }
    }

    @Override
    public void onTabReselect(int position) {

    }
}
